<script lang="ts" setup>
import type { NotificationItem } from '@vben/layouts';

import { computed, ref, watch, onMounted } from 'vue';

import { AuthenticationLoginExpiredModal } from '@vben/common-ui';
import { VBEN_DOC_URL, VBEN_GITHUB_URL } from '@vben/constants';
import { useWatermark } from '@vben/hooks';
import { Volume2 } from '@vben/icons';
import {
  BasicLayout,
  LockScreen,
  Notification,
  UserDropdown,
} from '@vben/layouts';
import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';
import { useRouter, useRoute } from 'vue-router';
import LoginForm from '#/views/_core/authentication/login.vue';
import { useUserDropdown } from '#/hooks/useUserDropdown';
import { getPublishedSysAnnListApi } from '#/api/lesson';
import { VbenIcon } from '@vben-core/shadcn-ui';
import AnnouncementDialog from '#/views/personal/modules/announcement-dialog.vue';

const notifications = ref<NotificationItem[]>([]);
const router = useRouter();
const userStore = useUserStore();
const accessStore = useAccessStore();
// const { destroyWatermark, updateWatermark } = useWatermark();
const showDot = computed(() =>
  notifications.value.some((item) => !item.isRead),
);

// 公告相关状态
const sysAnnList = ref<any[]>([]);
const currentAnnIndex = ref(0);
const showBanner = ref(true);

// 弹窗相关状态
const dialogVisible = ref(false);
const dialogCurrentIndex = ref(0);

// 当前显示的公告
const currentAnn = computed(() => {
  return sysAnnList.value[currentAnnIndex.value] || null;
});

// 是否是最后一条公告
const isLastAnn = computed(() => {
  return currentAnnIndex.value === sysAnnList.value.length - 1;
});

// 是否有公告数据
const hasAnnouncements = computed(() => {
  return sysAnnList.value.length > 0;
});

// 使用 UserDropdown hooks
const {
  avatar,
  userDropdownProps,
  handleLogout
} = useUserDropdown({
  showPersonalCenter: true,
  showUserMenu: true
});

function handleNoticeClear() {
  notifications.value = [];
}

function handleMakeAll() {
  notifications.value.forEach((item) => (item.isRead = true));
}

const getPublishedSysAnnList = async () => {
  const res = await getPublishedSysAnnListApi({ type: 'upgrade' });
  sysAnnList.value = res.data;
}

// 切换到下一条公告或关闭
const handleNext = () => {
  if (isLastAnn.value) {
    // 最后一条，关闭条幅
    showBanner.value = false;
  } else {
    // 切换到下一条
    currentAnnIndex.value++;
  }
}

// 点击公告内容，打开详情弹窗
const handleAnnouncementClick = () => {
  if (hasAnnouncements.value) {
    dialogCurrentIndex.value = currentAnnIndex.value;
    dialogVisible.value = true;
  }
}

// 弹窗事件处理
const handleDialogClose = () => {
  dialogVisible.value = false;
}

onMounted(() => {
  getPublishedSysAnnList();
});


</script>

<template>
  <BasicLayout @clear-preferences-and-logout="handleLogout">
    <template #logo-text>
      <div class="font-medium truncate max-w-[52] overflow-hidden text-ellipsis whitespace-nowrap"
        :title="userStore.tenant?.shortName">
        {{ userStore.tenant?.shortName }}
      </div>
    </template>
    <template #user-dropdown>
      <!-- 用户 -->
      <UserDropdown v-bind="userDropdownProps" @logout="handleLogout" />
    </template>
    <template #notification>
      <!-- 系统消息先隐藏 -->
      <Notification :dot="showDot" :notifications="notifications" @clear="handleNoticeClear"
        @make-all="handleMakeAll" />
    </template>
    <template #extra-tabbar>
      <!-- 公告条幅 -->
      <div v-if="showBanner && hasAnnouncements && currentAnn"
        class="absolute top-0 left-0 bg-[#CCE1F6] w-full h-full flex items-center justify-between px-[32px] py-[10px]">
        <!-- 公告图标 -->
        <div class="flex items-center flex-1">
          <VbenIcon :icon="Volume2" class="w-[20px] h-[20px] text-[#0067D1] fill-transparent" />
          <!-- 公告内容 -->
          <div class="text-[#333] text-sm flex-1 truncate mr-4 ml-[16px] cursor-pointer hover:text-[#0067D1]"
            @click="handleAnnouncementClick">
            重要公告：{{ currentAnn.title }}
          </div>
        </div>

        <!-- 下一条/关闭按钮 -->
        <button @click="handleNext"
          class="text-[#1890ff] text-sm hover:text-[#40a9ff] cursor-pointer flex-shrink-0 px-2 py-1 rounded hover:bg-white/50 transition-colors">
          {{ isLastAnn ? '关闭' : '下一条' }}
        </button>
      </div>
    </template>
    <!-- 登录过期弹窗
    <template #extra>
      <AuthenticationLoginExpiredModal v-model:open="accessStore.loginExpired" :avatar>
        <LoginForm />
      </AuthenticationLoginExpiredModal>
    </template>
    -->
    <template #lock-screen>
      <LockScreen :avatar @to-login="handleLogout" />
    </template>
  </BasicLayout>

  <!-- 公告详情弹窗 -->
  <AnnouncementDialog v-model="dialogVisible" v-model:current-index="dialogCurrentIndex" :announcements="sysAnnList"
    title="公告详情" @close="handleDialogClose" />
</template>

<style scoped>
/* 确保文本截断样式生效 */
.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
